<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="danger" @click="addDiaglogVisible=true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 列表区域 -->
      <el-table :data="roleList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom',i1==0?'bdtop':'','vcenter']"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag
                  type="danger"
                  closable
                  @close="removeRightById(scope.row,item1.id)"
                >{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级三级权限 -->
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row
                  :class="[i2===0?'':'bdtop','vcenter']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="info"
                      closable
                      @close="removeRightById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row}}</pre> -->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" icon="el-icon-edit">编辑</el-button>
            <el-button
              type="info"
              size="mini"
              icon="el-icon-delete"
              @click="removeRoleById(scope.row.id)"
            >删除</el-button>
            <el-button
              @click="showSetRightDialog(scope.row)"
              type="dark"
              size="mini"
              icon="el-icon-setting"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 定义添加对话框 -->
    <el-dialog @close="addDiaglogClose" title="添加用户" :visible.sync="addDiaglogVisible" width="30%">
      <el-form :model="addRoles" :rules="addRolesRules" ref="addRloesRef" label-width="70px">
        <el-form-item label="用户名" prop="Name">
          <el-input v-model="addRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="用户描述" prop="Desc">
          <el-input v-model="addRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="danger" @click="addRole">确定</el-button>
        <el-button @click="addDiaglogVisible=false">取消</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      @close="setRightClosed"
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="30%"
    >
      <el-tree
        show-checkbox
        :data="rightsList"
        :props="defaultProps"
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      roleList: [],
      addDiaglogVisible: false,
      addRoles: {
        roleName: "",
        roleDesc: "",
      },
      addRolesRules: {
        roleName: [
          { required: true, message: "必须输入用户名", trigger: "blur" },
        ],
        roleDesc: [{ required: false, message: "选填", trigger: "blur" }],
      },
      setRightDialogVisible: false,
      rightsList: [],
      // 树形控件绑定对象
      defaultProps: {
        label: "authName",
        children: "children",
      },
      defKeys: [],
      roleId: "",
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles")
      if (res.meta.status !== 200) {
        this.$message.error("数据获取失败")
      } else {
        this.roleList = res.data
        // console.log(res.data)
      }
    },
    async removeRightById(role, rightId) {
      const a = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err)
      if (a !== "confirm") {
        this.$message.info("已取消删除")
      } else {
        const { data: res } = await this.$http.delete(
          `roles/${role.id}/rights/${rightId}`
        )
        // console.log(res)
        if (res.meta.status != 200) {
          this.$message.error("删除失败")
        } else {
          role.children = res.data
        }
      }
    },
    addRole() {
      this.$refs.addRloesRef.validate(async (valid) => {
        // console.log(valid)
        // console.log(this.addRoles)
        if (!valid) {
          return
        } else {
          const { data: res } = await this.$http.post("roles", this.addRoles)
          if (res.meta.status !== 201) {
            this.$message.error("添加失败")
          } else {
            this.$message.success("添加成功")
            this.addDiaglogVisible = false
            this.getRolesList()
          }
        }
      })
    },
    addDiaglogClose() {
      this.$refs.addRloesRef.resetFields()
      this.addRoles = {
        roleName: "",
        roleDesc: "",
      }
    },
    async removeRoleById(id) {
      const a = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err)

      if (a !== "confirm") {
        this.$message.info("已取消删除")
      } else {
        const { data: res } = await this.$http.delete("roles/" + id)
        if (res.meta.status !== 200) {
          this.$message.error("删除失败")
        } else {
          this.$message.success("删除成功")
          this.getRolesList()
        }
      }
    },
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 获取所有权限数据
      const { data: res } = await this.$http.get("rights/tree")
      if (res.meta.status !== 200) {
        this.$message.error("获取权限列表失败")
      } else {
        this.rightsList = res.data
        // console.log(this.rightsList)
      }
      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 递归获取三级权限
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr)
      })
    },
    setRightClosed() {
      this.defKeys = []
    },
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      // console.log(keys)
      const idstr = keys.join(",")
      // console.log(idstr)
      // console.log(this.roleId)
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: idstr,
        }
      )

      if (res.meta.status !== 200) {
        this.$message.error("分配失败")
      } else {
        this.$message.success("分配成功")
        this.getRolesList()
        this.setRightDialogVisible = false
      }
    },
  },
}
</script>
<style lang="less" scoped>
.el-table {
  margin-top: 10px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>